import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { FolderOpen, Search, Merge } from "lucide-react";
import { useState, useEffect, useRef } from "react";
import { FileStatus } from '@/types';

export default function FileAnalyzer() {
  const [selectedPath, setSelectedPath] = useState<string>("");
  const [excelFiles, setExcelFiles] = useState<string[]>([]);
  const [isChecked, setIsChecked] = useState<boolean>(false);
  const [logs, setLogs] = useState<string[]>([]);
  const [status, setStatus] = useState<string>("就绪");
  const [fileList, setFileList] = useState<FileStatus[]>([]);

  const handleSelectFolder = async () => {
    try {
      const result = await window.electron.openDirectory();
      if (result.canceled) {
        addLog("取消选择文件夹");
        return;
      }
      const folderPath = result.filePaths[0];
      setSelectedPath(folderPath);
      setExcelFiles(result.excelFiles ? result.excelFiles : []);
      addLog(`已选择文件夹: ${folderPath}`);
      addLog(`发现 ${result.excelCount} 个 Excel 文件`);

      setStatus("已选择文件夹");
      setIsChecked(false); // 重置检查状态
    } catch (error) {
      addLog(`选择文件夹失败: ${(error as Error).message}`);
      setStatus("错误");
    }
  };

  const addLog = (message: string) => {
    setLogs(prev => [...prev, `[${new Date().toLocaleTimeString()}] ${message}`]);
  };

  const clearLogs = () => {
    setLogs([]);
    setStatus("就绪");
  };

  const exportLogs = () => {
    const logText = logs.join("\n");
    const blob = new Blob([logText], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `analysis-logs-${new Date().toISOString()}.txt`;
    a.click();
    URL.revokeObjectURL(url);
    addLog("日志已导出");
  };

  const handleAnalyze = async () => {
    if (!selectedPath || !excelFiles.length) {
      addLog("请先选择包含 Excel 文件的文件夹");
      return;
    }

    setStatus("检查中...");
    addLog("开始检查 Excel 文件...");

    try {
      const fileListResult = [];
      let hasAnyError = false; // 使用局部变量跟踪错误状态
      
      for (const file of excelFiles) {
        const fullPath = window.electron.joinPath(selectedPath, file);
        addLog(`正在检查: ${file}`);
        const analysis = await window.electron.analyzeExcel(fullPath);

        fileListResult.push({
          fileName: file,
          hasShexiaoSuliao: analysis.hasShexiaoSuliao ? analysis.hasShexiaoSuliao : false,
          hasShexiaoGuangdong: analysis.hasShexiaoGuangdong ? analysis.hasShexiaoGuangdong : false,
          hasShexiaoHainan: analysis.hasShexiaoHainan ? analysis.hasShexiaoHainan : false,
          hasYufuSuliao: analysis.hasYufuSuliao ? analysis.hasYufuSuliao : false,
          hasYufuGuangdong: analysis.hasYufuGuangdong ? analysis.hasYufuGuangdong : false,
          hasYufuHainan: analysis.hasYufuHainan ? analysis.hasYufuHainan : false,
        });
        
        if (!analysis.success) {
          hasAnyError = true; // 使用局部变量记录错误
          addLog(`检查失败: ${analysis.error}`);
        }
      }
      
      setFileList(fileListResult);

      addLog("所有 Excel 文件检查完成");
      
      if (hasAnyError) { // 使用局部变量判断
        setStatus("错误");
        setIsChecked(false);
      } else {
        setStatus("就绪");
        setIsChecked(true);
      }

    } catch (error) {
      setStatus("错误");
      addLog(`检查过程出错: ${(error as Error).message}`);
    }
  };

  const handleMerge = async () => {
    if (!selectedPath || !excelFiles.length) {
      addLog("请先选择包含 Excel 文件的文件夹");
      return;
    }
    setStatus("合并中...");
    addLog("开始合并 Excel 文件...");
    
    // 注册监听器
    const progressListener = window.electron.addMergeProgressListener((message) => {
      addLog(message);
    });

    try {
      const mergeResult = await window.electron.mergeExcel(selectedPath, fileList);
      if (mergeResult.success) {
        mergeResult.message && addLog(mergeResult.message);
        setStatus("合并完成");
      } else {
        // 处理失败情况
        addLog(`合并失败: ${mergeResult.error || '未知错误'}`);
        setStatus("错误");
      }
    }
    catch (error) {
      addLog(`合并过程出错: ${(error as Error).message}`);
      setStatus("错误");
    }
    finally {
      // 移除进度监听器
      window.electron.removeMergeProgressListener(progressListener);
    }
  }

  const textareaRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (textareaRef.current) {
      const textarea = textareaRef.current.querySelector('textarea');
      if (textarea) {
        textarea.scrollTop = textarea.scrollHeight;
      }
    }
  }, [logs]);

  const [version, setVersion] = useState<string>("");

  useEffect(() => {
    // 使用 async/await 处理 Promise
    const fetchVersion = async () => {
      try {
        const ver = await window.electron.getAppVersion();
        setVersion(ver);
      } catch (error) {
        console.error('获取版本号失败:', error);
      }
    };

    fetchVersion();
  }, []);

  return (
    <div className="h-screen flex flex-col bg-background p-6 space-y-6 overflow-hidden">
      {/* 主内容区域 */}
      <div className="flex-1 flex flex-col space-y-3 no-drag-region overflow-hidden">


        {/* 按钮区域 */}
        <div className="flex space-x-4">
          <Button onClick={handleSelectFolder}>
            <FolderOpen className="h-4 w-4" />
            选择文件夹
          </Button>
          <Button onClick={handleAnalyze} disabled={!selectedPath}>
            <Search className="h-4 w-4" />
            检查文件
          </Button>
          <Button onClick={handleMerge} disabled={!isChecked}>
            <Merge className="h-4 w-4" />
            合并台账
          </Button>
        </div>
        {/* 文件夹选择区域 */}
        <div className="space-y-2">
          <p className="text-sm text-muted-foreground truncate px-1">
            已选择: <span className="font-mono bg-muted/50 px-2 py-1 rounded">
              {selectedPath || "未选择文件夹"}
            </span>
          </p>
        </div>

        {/* 新的两栏布局 */}
        <div className="flex-1 flex flex-col space-y-4 overflow-hidden">
          {/* 左侧文件列表 */}
          <div className="h-1/2 flex flex-col space-y-3 overflow-hidden">
            <h2 className="text-lg font-semibold">文件列表</h2>
            <div className="flex-1 overflow-auto border rounded-md">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>文件名</TableHead>
                    <TableHead className="text-center">赊销-塑料</TableHead>
                    <TableHead className="text-center">赊销-广东</TableHead>
                    <TableHead className="text-center">赊销-海南</TableHead>
                    <TableHead className="text-center">预付-塑料</TableHead>
                    <TableHead className="text-center">预付-广东</TableHead>
                    <TableHead className="text-center">预付-海南</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {fileList.map((file, index) => (
                    <TableRow key={index}>
                      <TableCell>{file.fileName}</TableCell>
                      <TableCell className={`text-center ${!file.hasShexiaoSuliao ? "bg-muted" : ""}`}>
                        {file.hasShexiaoSuliao ? "✔" : "-"}
                      </TableCell>
                      <TableCell className={`text-center ${!file.hasShexiaoGuangdong ? "bg-muted" : ""}`}>
                        {file.hasShexiaoGuangdong ? "✔" : "-"}
                      </TableCell>
                      <TableCell className={`text-center ${!file.hasShexiaoHainan ? "bg-muted" : ""}`}>
                        {file.hasShexiaoHainan ? "✔" : "-"}
                      </TableCell>
                      <TableCell className={`text-center ${!file.hasYufuSuliao ? "bg-muted" : ""}`}>
                        {file.hasYufuSuliao ? "✔" : "-"}
                      </TableCell>
                      <TableCell className={`text-center ${!file.hasYufuGuangdong ? "bg-muted" : ""}`}>
                        {file.hasYufuGuangdong ? "✔" : "-"}
                      </TableCell>
                      <TableCell className={`text-center ${!file.hasYufuHainan ? "bg-muted" : ""}`}>
                        {file.hasYufuHainan ? "✔" : "-"}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

            </div>
          </div>

          {/* 右侧日志区域 */}
          <div className="h-1/2 flex flex-col space-y-3  overflow-hidden" ref={textareaRef}>
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold">日志</h2>
              <div className="flex space-x-2">
                <Button variant="outline" size="sm" onClick={clearLogs}>
                  清除日志
                </Button>
                <Button variant="outline" size="sm" onClick={exportLogs}>
                  导出日志
                </Button>
              </div>
            </div>

            <Textarea
              className="flex-1 font-mono text-sm bg-muted/50 resize-none overflow-auto"
              placeholder="日志将显示在这里..."
              readOnly
              value={logs.join("\n")}
            />
          </div>
        </div>

        {/* 状态栏 */}
        <div className="flex justify-between text-sm text-muted-foreground px-1">
          <span>状态: {status}</span>
          <span>版本: {version}</span>
        </div>
      </div>
    </div>
  );
}